package com.example.mydemo.controller.hc;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.mydemo.entity.Users;
import com.example.mydemo.entity.domain.AttendanceStatDTO;
import com.example.mydemo.mapper.UsersMapper;
import com.example.mydemo.model.tableVO;
import com.example.mydemo.service.IEmployeeService;
import com.example.mydemo.service.impl.AttendanceService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.*;
import java.net.URLEncoder;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;

@Controller
@RequestMapping()
public class AttendanceController {
    @Autowired
    private AttendanceService attendanceService;
    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private UsersMapper userMapper;

    @GetMapping("/getAttendancepage")
    @ResponseBody
//    @RequestParam String month
    public tableVO selectDeptCount(@RequestParam(defaultValue = "") String month,@RequestParam Long page, @RequestParam Long limit) throws ParseException {
        Page<AttendanceStatDTO> attendancepage = new Page<>(page, limit); // 创建分页对象，当前页为1，每页显示5条记录
        if(Objects.equals(month, "")){
            // 获取当前日期（基于系统默认时区）
            LocalDate currentDate = LocalDate.now();
            // 减去 1 个月（自动处理跨年，如 2024-01 → 2023-12）
            LocalDate lastMonth = currentDate.minusMonths(1);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
            String lastMonthStr = lastMonth.format(formatter);
            Page<AttendanceStatDTO> attendance = attendanceService.qureyByMouth(attendancepage,lastMonthStr ); // 查询当前页的员工考勤统计信息
            if (!attendance.getRecords().isEmpty()) {
                tableVO a = new tableVO();
                a.setCode(0L);
                a.setMsg("");
                a.setData(attendance.getRecords());
                a.setCount(attendance.getTotal());
                return a;
            }else{
                tableVO a = new tableVO();
                a.setMsg("无法统计该月数据");
                return a;
            }
        }else{
            Page<AttendanceStatDTO> attendance = attendanceService.qureyByMouth(attendancepage,month); // 查询当前页的员工考勤统计信息
            if (!attendance.getRecords().isEmpty()) {
                tableVO a = new tableVO();
                a.setCode(0L);
                a.setMsg("");
                a.setData(attendance.getRecords());
                a.setCount(attendance.getTotal());
                return a;
            }else {
                List<AttendanceStatDTO> AttendanceList = attendanceService.getAttendanceStat(month);
                attendanceService.batchInsertOrUpdate(AttendanceList);
                tableVO a = new tableVO();
                a.setCode(0L);
                a.setMsg("");
                a.setData(AttendanceList);
                a.setCount((long) AttendanceList.size());
                return a;
            }
        }
    }



    @GetMapping("/export")
    public void test( HttpServletResponse response,@RequestParam String month,@RequestParam Long departmentId,@RequestParam String departmentName) throws ParseException {

        attendanceService.export(response,month,departmentId,departmentName);
    }



    @GetMapping("/export2")
    @ResponseBody
    public void export2(HttpServletResponse response, HttpServletRequest request) throws IOException {
        try {
            String filenames = "111111";
            String userAgent = request.getHeader("User-Agent");
            if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
                filenames = URLEncoder.encode(filenames, "UTF-8");
            } else {
                filenames = new String(filenames.getBytes("UTF-8"), "ISO-8859-1");
            }
            response.setContentType("application/json.ms-exce");
            response.setCharacterEncoding("utf-8");
            response.addHeader("Content-Disposition", "filename=" + filenames + ".xlsx");

            // Step1：创建一个 QueryWrapper 对象
            QueryWrapper<Users> queryWrapper = new QueryWrapper<>();

            // Step2： 构造查询条件
            queryWrapper
                    .select("*");

            // Step3：执行查询
            List<Users> userList = userMapper.selectList(queryWrapper);

            EasyExcel.write(response.getOutputStream(), Users.class).sheet("sheet").doWrite(userList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


//        List<String> row1 = CollUtil.newArrayList("aa", "bb", "cc", "dd");
//        List<String> row2 = CollUtil.newArrayList("aa1", "bb1", "cc1", "dd1");
//        List<String> row3 = CollUtil.newArrayList("aa2", "bb2", "cc2", "dd2");
//        List<String> row4 = CollUtil.newArrayList("aa3", "bb3", "cc3", "dd3");
//        List<String> row5 = CollUtil.newArrayList("aa4", "bb4", "cc4", "dd4");
//
//        List<List<String>> rows = CollUtil.newArrayList(row1, row2, row3, row4, row5);
//        ExcelWriter writer = ExcelUtil.getWriter(true);
//        writer.passCurrentRow();
//        writer.merge(row1.size() - 1, "测试标题");
//        writer.write(rows, true);
//        String fileName = "Test.xlsx";
//        response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
//        // 定义下载的类型，标明是excel文件
//        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//        OutputStream os = response.getOutputStream();
//        writer.flush(os);
//        os.flush();
//        os.close();
//        writer.close();
    }

    /*导出接口*/
//    @GetMapping("/export")
//    @ResponseBody
//    public void export(HttpServletResponse response) throws IOException {
//        try {
//            // 查询数据（假设返回非空列表）
//            List<Employee> list = employeeService.list(new Page<>(1, 5));
//            if (list == null || list.isEmpty()) {
//                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "无数据可导出");
//                return;
//            }
//
//            // 创建 Excel 写入器（自动关闭流）
//            try (ExcelWriter writer = ExcelUtil.getWriter(true)) {
//                // 设置表头别名（中文列名）
//                writer.addHeaderAlias("employee_id", "序号");
//                writer.addHeaderAlias("name", "姓名");
//                writer.addHeaderAlias("age", "年龄");
//                writer.addHeaderAlias("job_title", "职位");
//                writer.addHeaderAlias("hire_date", "入职时间");
//                writer.addHeaderAlias("create_time", "创建时间");
//
//                // 写入数据（强制输出标题行）
//                writer.write(list, true);
//
//                // 设置响应头
//                String fileName = "雇员信息";
//                String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replace("+", "%20");
//                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//                response.setHeader("Content-Disposition",
//                        "attachment; filename=" + encodedFileName + ".xlsx" + "; filename*=UTF-8''" + encodedFileName + ".xlsx");
//
//                // 输出流写入响应（自动刷新和关闭）
//                ServletOutputStream out = response.getOutputStream();
//                writer.flush(out, true);
//                out.flush(); // 确保流数据完全发送
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "导出失败：" + e.getMessage());
//        }
//    }
